package app.controller;

import java.util.List;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpSession;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import app.config.Config;
import app.domain.Article;
import app.domain.Result;
import app.service.CommunityService;

@Controller
public class CommunityController {
	public static Logger logger=LogManager.getLogger(CommunityController.class);
	@Autowired
	private CommunityService communityService;
	
	@RequestMapping("community")
	public String showCommunity(HttpServletRequest request){
		List<Article> articles = communityService.showArticle();
		request.setAttribute("articles", articles);
		return "user/community2";
	}
	
	@RequestMapping(value = "/comment/{articleId}",method = RequestMethod.GET)
	public String showComment(@PathVariable("articleId") String articleId,HttpServletRequest request){
		System.out.println(articleId);
		List<Article> articles = communityService.findArticle(articleId);
		request.setAttribute("topArticle", articles.get(articles.size()-1));
		articles.remove(articles.size()-1);
		request.setAttribute("articles", articles);
		return "user/comment2";
	}
	
	@RequestMapping("showAddArticle")
	public String showAddArticle(){
		return "user/addArticle";
	}
	
	@RequestMapping(value="addArticle",method=RequestMethod.POST  )
	@ResponseBody
	public Result add(String title,String content,int accountId){
		Article article = new Article();
		article.setTitle(title);
		article.setContent(content);
		article.setAccountId(accountId);
		article.setPid(0);
		communityService.addArticle(article);
		Result result=new Result(Config.SUCCESS_CODE,"success");
		return result;
	}
	
	@RequestMapping(value="replyArticle",method=RequestMethod.POST )
	public String replyArticle(String content,int accountId,int articleId,HttpServletRequest request){
		Article article = new Article();
		article.setTitle("");
		article.setContent(content);
		article.setAccountId(accountId);
		article.setPid(articleId);
		System.out.print(article.toString());
		communityService.addArticle(article);
		communityService.replyAdd1(articleId);
		
		List<Article> articles = communityService.findArticle(String.valueOf(articleId));
		request.setAttribute("topArticle", articles.get(articles.size()-1));
		articles.remove(articles.size()-1);
		request.setAttribute("articles", articles);
		return "user/comment2";
	}
}
